package com.yanfei.zero.application.handler.log;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Order(1)
@Slf4j
public class LogAspect {

	@Pointcut("@annotation(AddLog)")
	public void logPointcut() {
	}

	@Around("logPointcut()")
	public Object logHandler(ProceedingJoinPoint process) throws Throwable {
		Map<String, Object> data = new HashMap<>();
		long startTime = System.currentTimeMillis();
		MethodSignature methodSignature = (MethodSignature) process.getSignature();
		Method method = methodSignature.getMethod();
		String methodName = method.getName();
		String className = method.getDeclaringClass().getName();
		Object[] args = process.getArgs();
		Object result = null;
		try {
			result = process.proceed(args);
		} catch (Throwable throwable) {
			String exception = throwable.getClass() + ":" + throwable.getMessage();
			long costTime = System.currentTimeMillis() - startTime;
			log.error("请求耗时：{}，请求类名：{}，请求方法：{}，请求参数:{}，请求结果：{}", costTime, className, methodName,
					JSONUtil.toJsonPrettyStr(args[0]), exception);
			data.put("code", 500);
			data.put("msg", "服务异常,请联系管理员");
			return data;
		}
		long costTime = System.currentTimeMillis() - startTime;
		log.info("请求耗时：{}，请求类名：{}，请求方法：{}，请求参数:{}，请求结果：{}", costTime, className, methodName,
				JSONUtil.toJsonPrettyStr(args[0]), result);
		data.put("code", 200);
		data.put("msg", "success");
		data.put("data", result);
		return data;
	}
}
